import {
  Button,
  Card,
  Col,
  DatePicker,
  Drawer,
  Flex,
  Form,
  Input,
  message,
  Radio,
  Row,
  Select,
  Space,
  Table,
  Tag,
} from "antd";
import { useDispatch, useSelector } from "react-redux";
import {
  addUser,
  IUserType,
  updateUser,
} from "../../../store/slices/usersSlice.ts";
import { RootState } from "../../../store";
import { useState } from "react";
import { nanoid } from "@reduxjs/toolkit";
import { UserAddOutlined } from "@ant-design/icons";

const genders = [
  { value: 0, label: "男" },
  { value: 1, label: "女" },
];

export default function User() {
  const dispatch = useDispatch();
  const [messageApi, contextHolder] = message.useMessage();

  // 所有角色
  const roles = useSelector((state: RootState) => state.users.roles);
  // 筛选指定角色 * 所有角色 -1 | 请选择 -2
  const [currentUserRole, setCurrentUserRole] = useState(-1);
  // 筛选指定性别 * 所有性别 -1 | 男 0 | 女 1
  const [currentGender, setCurrentGender] = useState(-1);
  // 筛选用户
  const select: IUserType[] = useSelector((state: RootState) => {
    let users = state.users.users;
    if (currentUserRole > -1) {
      users = users.filter((user) => user.role === currentUserRole);
    }
    if (currentGender > -1) {
      users = users.filter((user) => user.gender === currentGender);
    }
    return users;
  });
  // 编辑用户Drawer是否可见
  const [editUserDrawer, setEditUserDrawer] = useState(false);
  // 编辑模式
  const [editMode, setEditMode] = useState(false);
  // 用户
  const [currentUser, setCurrentUser] = useState<IUserType>({
    id: "",
    nike: "",
    role: -2,
    gender: 0,
    phoneNumber: "",
    createTime: "",
  });
  // 打开用户编辑抽屉
  const openEditUserDrawer = (user: IUserType | null) => {
    if (user) {
      setCurrentUser(user);
      setEditMode(true);
    } else {
      setCurrentUser({
        id: "",
        nike: "",
        gender: 0,
        role: -2,
        phoneNumber: "",
        createTime: "",
      });
    }
    setEditUserDrawer(true);
  };
  // 关闭用户编辑抽屉
  const closeEditUserDrawer = () => {
    setEditUserDrawer(false);
    setEditMode(false);
  };

  const DrawerExtra = () => {
    let clickHandler = () => {
      // 新增用户
      closeEditUserDrawer();
      dispatch(addUser({ ...currentUser, id: nanoid() }));
      messageApi.success(`新增${currentUser.nike}信息成功`).then();
    };

    if (editMode) {
      clickHandler = () => {
        // 修改用户
        closeEditUserDrawer();
        dispatch(updateUser(currentUser));
        messageApi.success(`修改${currentUser.nike}信息成功`).then();
      };
    }

    return (
      <Space>
        <Button type="primary" onClick={clickHandler}>
          {editMode ? "修改" : "新增"}
        </Button>
        <Button onClick={closeEditUserDrawer}>取消</Button>
      </Space>
    );
  };

  return (
    <>
      <Flex vertical={true} gap="small" style={{ padding: "10px" }}>
        <Card title="筛选">
          <Space>
            <Input.Search placeholder="请输入用户名" enterButton="搜索" />
            <Select
              options={[{ label: "所有职位", value: -1 }, ...roles]}
              defaultValue={-1}
              style={{ width: 120 }}
              onSelect={(v) => setCurrentUserRole(v)}
            />
            <Select
              options={[{ label: "所有性别", value: -1 }, ...genders]}
              defaultValue={-1}
              style={{ width: 120 }}
              onSelect={(v) => setCurrentGender(v)}
            />
          </Space>
        </Card>
        <Card
          title="用户列表"
          extra={
            <Space>
              <Button
                icon={<UserAddOutlined />}
                type="primary"
                onClick={() => openEditUserDrawer(null)}>
                新增用户
              </Button>
              <Button>批量管理</Button>
            </Space>
          }>
          <Table<IUserType> dataSource={select} rowKey="id">
            <Table.Column title="账号" dataIndex="id" />
            <Table.Column title="姓名" dataIndex="nike" />
            <Table.Column
              title="性别"
              dataIndex="gender"
              render={(text) => (text == 0 ? "男" : "女")}
            />
            <Table.Column
              title="职位"
              dataIndex="role"
              render={(text) => {
                const r = roles.find((role) => role.value === text);
                if (r) return <Tag color={r.color}>{r.label}</Tag>;
                return <Tag color="error">职位被删除</Tag>;
              }}
            />
            <Table.Column title="手机号码" dataIndex="phoneNumber" />
            <Table.Column title="备注" />
            <Table.Column title="创建时间" dataIndex="createTime" />
            <Table.Column
              title="操作"
              key="action"
              render={(_text, record: IUserType) => (
                <Space size="middle">
                  <a onClick={() => openEditUserDrawer(record)}>编辑</a>
                  <a>删除</a>
                </Space>
              )}
            />
          </Table>
        </Card>
      </Flex>
      <Drawer
        extra={<DrawerExtra />}
        open={editUserDrawer}
        onClose={closeEditUserDrawer}
        size="large"
        closeIcon={null}
        title={editMode ? "修改用户" : "新增用户"}>
        <Form>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="姓名">
                <Input
                  value={currentUser.nike}
                  onChange={(e) => {
                    setCurrentUser({ ...currentUser, nike: e.target.value });
                  }}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="职位">
                <Select
                  options={[{ label: "请选择", value: -2 }, ...roles]}
                  value={currentUser.role}
                  onChange={(v: number) => {
                    setCurrentUser({ ...currentUser, role: v });
                  }}
                />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="电话号码"
                validateStatus=""
                rules={[{ required: true, message: "请填写电话号码" }]}>
                <Input
                  value={currentUser.phoneNumber}
                  onChange={(e) => {
                    setCurrentUser({
                      ...currentUser,
                      phoneNumber: e.target.value,
                    });
                  }}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="性别">
                <Radio.Group
                  block
                  options={genders}
                  value={currentUser.gender}
                  optionType="button"
                  buttonStyle="solid"
                  onChange={(e) => {
                    setCurrentUser({ ...currentUser, gender: e.target.value });
                  }}
                />
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <Form.Item label="创建日期">
                <DatePicker disabled={true} />
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <Form.Item label="备注">
                <Input.TextArea
                  rows={4}
                  autoSize={true}
                  style={{ resize: "none" }}
                />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Drawer>
      {contextHolder}
    </>
  );
}
